<script setup>
import AddClassifyBtn from '@/components/AddClassifyBtn.vue'
import { ref, onMounted, inject } from 'vue'
import { RouterLink } from 'vue-router'
import { useAddClassificationService, useGetClassificationsService, useDeleteClassificationService } from '@/api/task'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
// 分类列表
const classifyList = ref([])  // 使用ref,确保分类列表是响应式的
// 从父组件（LayoutPage）注入刷新方法
const refreshData = inject('refreshData', () => {})
// 从后端获取分类列表
const getClassificationList = async () => {
  const res = await useGetClassificationsService({ user_id: userStore.userId })
  console.log('userStore.userId:', userStore.userId)
  console.log('从后端获取的分类列表res:', res)
  classifyList.value = res.data.data
}
// 立即调用执行获取分类函数
onMounted(() => {
  getClassificationList()
})
// 传给父组件提醒刷新分类列表事件
const emit = defineEmits(['refreshClassify'])
// 添加分类
const addClassify = async (classify_name) => {
  // 添加分类
  const res = await useAddClassificationService({
    classify_name: classify_name,
    user_id: userStore.userId
  })
  if(res.data.status === 1) {
    ElMessage.error(res.data.message)
  } else {
    ElMessage.success(res.data.message)
  }
  // 重新获取分类列表
  getClassificationList()
  // 提醒LayoutPage更新分类数据
  emit('refreshClassify')
  // 提醒LayoutPage更新任务数据
  refreshData()
}
// 删除分类
const deleteClassifyList = async (id) => {
  // 前端实现删除
  // classifyList.value = classifyList.value.filter(item => item.id !== id)
  // 调用后端接口删除
  const res = await useDeleteClassificationService({ id })
  if(res.data.status === 1) {
    ElMessage.error(res.data.message)
  } else {
    ElMessage.success(res.data.message)
  }
  // 重新获取分类列表
  getClassificationList()
  // 提醒LayoutPage更新分类数据
  emit('refreshClassify')
  // 提醒LayoutPage更新任务数据
  refreshData()
}
// 拖动开始
const dragstart = (index, event) => {
  event.dataTransfer.setData("text", index)
  console.log("您已成功拖动元素" + index)    
}
// 进行放置
const drop = (targetIndex, list, event) => {
  const draggedIndex = parseInt(event.dataTransfer.getData("text"), 10); // 转换为整数
  const draggedTask = list[draggedIndex]; // 获取拖拽的任务
  list.splice(draggedIndex, 1); // 先移除原位置的元素
  list.splice(targetIndex, 0, draggedTask); // 在新位置插入
  console.log("drop", event)
  console.log('targetIndex:' + targetIndex + '.')
  console.log('draggedIndex:' + draggedIndex + '.')
  console.log(list)
}
// 放置位置 - 阻止默认事件,即允许放置
const dragover = (event) => {
  event.preventDefault()
}
</script>

<template>
  <!-- 任务添加页 -->
  <div class="nav">
    <div class="top">
      <ul>
        <li>
          <RouterLink to="/tasks/today" class="row">
            <span class="iconfont">&#xe6b0;</span>
            <span class="classifyName">今天</span>
          </RouterLink>
        </li>
        <li>
          <RouterLink to="/tasks/sevendays" class="row">
            <span class="iconfont">&#xe705;</span>
            <span class="classifyName">最近7天</span>
          </RouterLink>
        </li>
        <li>
          <RouterLink to="/tasks/all" class="row">
            <span class="iconfont" style="font-size: 19px;">&#xe7e6;</span>
            <span class="classifyName">全部事项</span>
          </RouterLink>
        </li>
      </ul>
    </div>
    <div class="middle">
      <div class="list">
        <span style="font-weight: 700;">清单</span>
        <!-- 添加分类按钮 -->
        <AddClassifyBtn @getclassifyName="addClassify"></AddClassifyBtn>
      </div>
      <!-- 清单分类列表 -->
      <ul>
        <li draggable="true" 
         @dragstart="dragstart(index, $event)" 
         @drop.prevent="drop(index, classifyList, $event)" 
         @dragover.prevent="dragover" 
         v-for="(item, index) in classifyList" 
         :key="item.id"
        >
          <RouterLink :to="{
            path: `${item.classify_name}`,
            query: { classify_id: item.id }
          }" class="row">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="拖动调整顺序"
              placement="bottom"
            >
              <span class="iconfont">&#xe790;</span>
            </el-tooltip>
            <span class="classifyName">{{ item.classify_name }}</span>
            <DeleteClassifyBtn :deleteClick="() => deleteClassifyList(item.id)"></DeleteClassifyBtn>
          </RouterLink>
        </li>
      </ul>
    </div>
    <div class="bottom">
      <ul>
        <li>
          <RouterLink to="/tasks/finished" class="row">
            <span class="iconfont">&#xe628;</span>
            <span class="classifyName">已完成</span>
          </RouterLink>
        </li>
        <li>
          <RouterLink to="/tasks/deleted" class="row">
            <span class="iconfont">&#xe61a;</span>
            <span class="classifyName">垃圾桶</span>
          </RouterLink>
        </li>
      </ul>
    </div>
  </div>
  <!-- 三级路由出口 -->
  <RouterView class="container"></RouterView>
</template>

<style lang="less" scoped>
.nav {
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ccc;
  padding: 0 10px;
  overflow: auto;

  .top,
  .middle {
    border-bottom: 1px solid #ccc;
  }

  .top,
  .middle,
  .bottom {
    padding: 20px 0 0;

    .row {
      display: flex;
      align-items: center;
      margin: 10px 5px;
      padding: 10px 5px;
      text-decoration: none;

      .box-item {
        width: 110px;
        margin-top: 10px;
      }

      .iconfont {
        font-size: 23px;
        color: #a3a3a3;
        cursor: pointer;
      }

      .classifyName {
        width: 37vh;
        margin-left: 10px;
        font-size: 14px;
        overflow: hidden;
        color: #000;
      }
    }

    .router-link-active {
      border-radius: 5px;
      background-color: #f1f1f1;
    }

    .list:hover,
    .row:hover {
      border-radius: 5px;
      background-color: #f1f1f1;

       /deep/.point {
        display: block;
      }
    }

    .list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 0 10px;
      padding: 5px;
      font-size: 13px;
      color: #b8b8b8;
    }
  }
}

.container {
  display: flex;
}

// 超小屏幕下
@media screen and (max-width: 575px) {
  .nav {
    display: none;
  }
}

// 小屏幕下
@media screen and (min-width: 576px) {
  .nav {
    width: 15%;
    min-width: 216px;
  }
}

// 中等、大、超大屏幕下
@media screen and (min-width: 768px) {
  .nav {
    width: 15%;
    min-width: 216px;
  }
}
</style>
